import { useEffect, useMemo, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import dayjs from 'dayjs'
import classnames from 'classnames'
import { Card, Collapse, Tag, Timeline } from 'antd'

import { VCenterEmpty } from '@/components/VCenterEmpty'
import { eventBus } from '@oBiz/TrackOrder/Detail/utils'
import { apiGetWaybillNumberRouteInfo } from './apis'
import { IWaybillNumberRouteInfo } from './interface'
import styles from './styles.module.less'

interface IProps {
  waybillNo: string
}

export const TransferOrderNumRoute = (props: IProps) => {
  const { waybillNo } = props
  const [waybillNoRouteInfo, setWaybillNoRouteInfo] = useState<IWaybillNumberRouteInfo[]>([])
  const [loading, setLoading] = useState<boolean>(false)

  // 请求接口
  const initData = useMemoizedFn(async (isinit?: boolean) => {
    try {
      if (isinit) setLoading(true)
      const data = await apiGetWaybillNumberRouteInfo(waybillNo)
      setWaybillNoRouteInfo(data)
    } finally {
      if (isinit) setLoading(false)
    }
  })

  /** 路由items */
  const items = useMemo(() => {
    return waybillNoRouteInfo.map(item => {
      const childrenItem = (item.routeInfoList || []).map((child, index) => {
        return {
          label: (
            <div className={styles.textTime}>
              {child.eventTimeIso ? dayjs(child.eventTimeIso).$formatSmart($F_YMDHms) : ''}
            </div>
          ),
          children: (
            <div className={styles.routeContain}>
              <div className={classnames(styles.textNew, index > 0 ? styles.textFilter : '')}>{child.eventDetail}</div>
            </div>
          ),
          color: index === 0 ? 'blue' : 'gray',
        }
      })
      return {
        key: item.trackingNumber,
        label: (
          <div className={styles.collapse_left}>
            {item.logisticsCompany}:{item.trackingNumber}
          </div>
        ),
        children: <Timeline mode="left" items={childrenItem} />,
        extra: <Tag>{item.latestStatus}</Tag>,
      }
    })
  }, [waybillNoRouteInfo])

  // 转单号变更
  useEffect(() => eventBus.on('transferOrderNumChanged', () => initData()), [initData])

  useEffect(() => {
    initData(true)
  }, [initData, waybillNo])

  return (
    <Card className={styles.card} title="转单号路由" loading={loading}>
      {waybillNoRouteInfo.length <= 0 ? (
        VCenterEmpty.render()
      ) : (
        <div className={styles.box}>
          <Collapse accordion expandIconPosition="end" items={items} />
        </div>
      )}
    </Card>
  )
}
